package com.atguigu.educenter.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantPropertiesUtil;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exception.GuliException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller//注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
public class WxApiController {


    @Autowired
    private UcenterMemberService memberService;

    //跳转二维码页面接口
    @GetMapping("/login")
    public String genQrConnect(HttpSession session) {

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";


        // 回调地址，对地址进行编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new GuliException(20001, e.getMessage());
        }


        //设置上面%s占位符的值
        String url = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL,
                "atguigu"
        );
        return "redirect:" + url;
    }


    //获取扫描人信息，添加数据
    @GetMapping("/callback")
    public String callback(String code, String state){

        try {
            //获取code值

            //向认证服务器发送请求换取access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            //拼接三个参数，id，密钥和code值
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            //使用httpclient发送请求返回结果
            String accessToken = HttpClientUtils.get(accessTokenUrl);

            //从accessToken 里面获取出两个值，
            //解析json字符串
            Gson gson = new Gson();
            HashMap map = gson.fromJson(accessToken, HashMap.class);
            String access_token = (String)map.get("access_token"); ////转换为map集合
            String openid = (String)map.get("openid");


            //把扫码人信息添加到数据库，先判断数据表里是否存在相同数据
            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member == null) { //如果查询出来的数据为空则执行下面添加方法。

                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                //拼接两个参数
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //获取返回userInfo字符串的扫描人信息，解析为json字符串
                HashMap<String, Object> mapUserInfo = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String)mapUserInfo.get("nickname");//获取用户昵称
                String headimgurl = (String)mapUserInfo.get("headimgurl");//获取用户头像


                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }

            //使用jwt把member对象转换为token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());


            //扫码登录之后回到首页面
            return "redirect:http://localhost:3000?token=" + token;
        } catch (Exception e) {
            throw new GuliException(201,"登录失败");
        }
    }
}
